package com.jm.member.common.messages.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.jm.member.common.core.exception.BaseException;
import com.jm.member.common.messages.config.WeChartConfig;
import com.jm.member.common.messages.enmus.WeChartLanguageEnum;
import com.jm.member.common.messages.entity.TicketResponse;
import com.jm.member.common.messages.entity.WeChartResponse;
import com.jm.member.common.messages.entity.WeChartUserInfo;
import com.jm.member.common.messages.entity.WechatAppletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@ImportAutoConfiguration(WeChartConfig.class)
@ConditionalOnProperty(name = "wechart.enabled", havingValue = "true")
public class WeChartService {
    private static final Logger logger = LoggerFactory.getLogger(WeChartService.class);
    @Autowired
    WeChartConfig weChartConfig;


    public WeChartResponse getAccessToken(String code) {
//        Map map=new HashMap();
//        map.put("appid",weChartConfig.getAppid());
//        map.put("secret",weChartConfig.getSecret());
//        map.put("code",code);
//        map.put("grant_type","authorization_code");
        logger.info("weChartConfig.Appid:" + weChartConfig.getAppid());
        logger.info("weChartConfig.secret:" + weChartConfig.getSecret());
        logger.info("weChartConfig.code:" + code);
        String comUrl = weChartConfig.getGetAccessTokenUrl() + "?appid=" + weChartConfig.getAppid() + "&secret=" + weChartConfig.getSecret() + "&code=" + code + "&grant_type=authorization_code";
        String body = HttpRequest.get(comUrl).execute().body();
        logger.info("wechartConfig:" + body);
        if (StrUtil.isEmpty(body)) {
            throw new BaseException(500, "微信获取AccessToken失败");
        }
        return JSONUtil.toBean(body, WeChartResponse.class);
    }

    ;

    //  获取微信小程序token
    public WechatAppletResponse getWeAppletUserInfo(String code) {
        String comUrl = "https://api.weixin.qq.com/sns/jscode2session" + "?appid=" + weChartConfig.getAppid() + "&secret=" + weChartConfig.getSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        logger.info("request_url:" + comUrl);
        String body = HttpRequest.get(comUrl).execute().body();
        logger.info("wechat_request_body:" + body);
        if (StrUtil.isEmpty(body)) {
            throw new BaseException(500, "微信获取AccessToken失败");
        }
        return JSONUtil.toBean(body, WechatAppletResponse.class);
    }

    public WeChartResponse refreshToken(String refresh_token) {
        Map map = new HashMap();
        map.put("appid", weChartConfig.getAppid());
        map.put("refresh_token", refresh_token);
        map.put("grant_type", "refresh_token");
        String body = HttpRequest.get(weChartConfig.getRefreshToeknUrl()).form(map).execute().body();
        if (StrUtil.isEmpty(body)) {
            throw new BaseException(500, "微信刷新AccessToken失败");
        }
        return JSONUtil.toBean(body, WeChartResponse.class);
    }

    public WeChartUserInfo getWeChartUserInfo(String access_token, String openid, WeChartLanguageEnum lang) {
        Map map = new HashMap();
        map.put("access_token", access_token);
        map.put("openid", openid);
        map.put("lang", lang.getValue());
        String body = HttpRequest.get(weChartConfig.getGetUserInfoUrl()).form(map).execute().body();
        if (StrUtil.isEmpty(body)) {
            throw new BaseException(500, "获取微信用户信息失败");
        }
        return JSONUtil.toBean(body, WeChartUserInfo.class);
    }

    /**
     * 获取分享的access_token
     * @return
     */
    public WeChartResponse getShareAccessToken(){
        String shareAccessTokenUrl = weChartConfig.getShareAccessTokenUrl();
        logger.info("weChartConfig.Appid:" + weChartConfig.getAppid());
        logger.info("weChartConfig.secret:" + weChartConfig.getSecret());
        String comUrl = shareAccessTokenUrl + "?grant_type=client_credential&appid=" + weChartConfig.getAppid() + "&secret=" + weChartConfig.getSecret();
        String body = HttpRequest.get(comUrl).execute().body();
        logger.info("getShareAccessToken:" + body);
        if (StrUtil.isEmpty(body)) {
            throw new BaseException(500, "微信获取AccessToken失败");
        }
        return JSONUtil.toBean(body, WeChartResponse.class);
    }

    /**
     * 获取分享的ticket
     * @return
     */
    public WeChartResponse getShareTicket(String accessToken){
        String shareTicketUrl = weChartConfig.getShareTicketUrl();
        logger.info("weChartConfig.Appid:" + weChartConfig.getAppid());
        logger.info("weChartConfig.secret:" + weChartConfig.getSecret());
        String comUrl = shareTicketUrl + "?access_token="+accessToken+"&type=jsapi";
        String body = HttpRequest.get(comUrl).execute().body();
        logger.info("getShareTicket:" + body);
        if (StrUtil.isEmpty(body)) {
            throw new BaseException(500, "微信获取AccessToken失败");
        }
        return JSONUtil.toBean(body, WeChartResponse.class);
    }

    /**
     * 获得分享 加密后的Ticket
     * @param url
     * @return
     */

    public  TicketResponse getTicketResponse(String ticket,String url){
        url = StrUtil.subBefore(url, "#", true);//排除#号;
        String timestamp = StrUtil.toString(new Date().getTime()/1000);
        String noncestr = weChartConfig.getNoncestr();
        StringBuilder sb=new StringBuilder();
        sb.append("jsapi_ticket=");
        sb.append(ticket);
        sb.append("&");
        sb.append("noncestr=");
        sb.append(noncestr);
        sb.append("&");
        sb.append("timestamp=");
        sb.append(timestamp);
        sb.append("&");
        sb.append("url=");
        sb.append(url);
        String ticketEncode = SecureUtil.sha1(sb.toString());
        TicketResponse response=new TicketResponse();
        response.setAppId(weChartConfig.getAppid());
        response.setTimestamp(timestamp);
        response.setSignature(ticketEncode);
        response.setJsapiTicket(ticket);
        response.setNonceStr(noncestr);
        response.setRawString(sb.toString());
        response.setUrl(url);
        return response;
    }

    public void setWeChartConfigAppid(String appid) {
        weChartConfig.setAppid(appid);
    }

    public void setWeChartConfigAppSecret(String appSecret) {
        weChartConfig.setSecret(appSecret);
    }

}
